from rest_framework import serializers, status
from django.contrib.auth import get_user_model
from rest_framework_simplejwt.exceptions import AuthenticationFailed

User = get_user_model()
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django.contrib.auth import authenticate


# 自定义登录序列化器
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        request = self.context.get('request')
        username = attrs.get("username")
        password = attrs.get("password")

        # 使用自定义认证逻辑（支持用户名/邮箱登录）
        user = authenticate(
            request=request,
            username=username,
            password=password
        )

        # 用户不存在或密码错误时的统一提示（安全考虑不区分具体原因）
        if not user:
            raise AuthenticationFailed({
                'status': 'error',
                'code': 'authentication_failed',
                'message': '无效的用户名或密码'
            })

        # 检查用户是否激活
        if not user.is_active:
            raise AuthenticationFailed({
                'status': 'error',
                'code': 'account_disabled',
                'message': '账户已被禁用'
            })

        # 通过所有检查后生成 token
        data = super().validate(attrs)

        # 自定义响应格式
        return {
            'status': 'success',
            'code': status.HTTP_200_OK,
            'data': {
                'access': data['access'],
                'refresh': data['refresh'],
                'user_id': self.user.id  # 可选：返回用户ID
            }
        }


class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    is_admin = serializers.BooleanField(default=False)  # 添加管理员判断字段

    class Meta:
        model = User
        fields = ('username', 'password', 'is_admin','email',)

    def create(self, validated_data):
        is_admin = validated_data.pop('is_admin', False)  # 获取并移除管理员字段
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            email=validated_data.get('email', '')
        )
        if is_admin:
            user.is_staff = True  # 设置用户为管理员
        user.save()
        return user




class UserProfileSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()  # 使用自定义方法返回头像的URL

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'avatar', 'bio', 'contact_info', 'birthday', 'gender', 'address',
                  'social_links', 'website', 'phone_number', 'last_login','avatar_url']

    def get_avatar_url(self, obj):
        """替换 avatar 中的 IP 地址"""
        request = self.context.get('request')
        if request and obj.avatar:
            # 构建完整的URL并替换IP
            full_url = request.build_absolute_uri(obj.avatar.url)
            return full_url.replace('0.0.0.0:8053', 'www.zywblog.com')  # 将 'yourdomain.com' 替换为你的实际域名或IP
        return None

    def update(self, instance, validated_data):
        # 如果用户上传了新的头像
        avatar = validated_data.get('avatar', None)
        if avatar:
            instance.avatar = avatar

        # 更新其他字段
        instance.username = validated_data.get('username', instance.username)
        instance.email = validated_data.get('email', instance.email)
        instance.bio = validated_data.get('bio', instance.bio)

        instance.save()
        return instance



